package siena.dbslayer;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import siena.Column;
import siena.Id;
import siena.Model;
import siena.Table;

public class ModelHelper {

	public static  boolean isId (Field field) {
		
		return ReflectionUtil.hasAnnotation(field, Id.class);
	}
	
	public static Map<String, String> getPropertyColumnNameIds (Object model) {
		
		Map<String, String> propColumns = new HashMap<String, String> ();
		
		Collection<Field> fields =  ReflectionUtil.getFields(model.getClass());
		
		for (Field field : fields) {
			
			if (isId (field)) {
				
				propColumns.put(field.getName(), getColumnName(field));
			}
		}
		
		return propColumns;
	} // getPropertyColumnIds
	
	public static String getColumnName (Field field) {
		
		String columnName = field.getName();
		
		Column column = field.getAnnotation(Column.class);
		
		if (null != column) {
			
			columnName = column.value()[0];
		}
		
		return columnName;
	} // getColumnName.

	/**
	 * Get the table name of the class, if the object doesn't has table
	 * annotation, returns the class name.
	 * 
	 * @param clazz
	 *            Class
	 * @return String
	 */
	public static String getTableName(Class<?> clazz) {

		Table t = clazz.getAnnotation(Table.class);
		return (t == null) ? clazz.getName() : t.value();
	} // getTableName.

	/**
	 * Get Column Names, get the Column annotations or Columns annotations.
	 * 
	 * @param field
	 *            Field
	 * @return List<String>
	 */
	public static Collection<String> getColumnNames(Field field) {

		Collection<String> columnNames = null;
		Column c = field.getAnnotation(Column.class);
		if (c != null) {

			columnNames = Arrays.asList(c.value());
		}

		return columnNames;
	} // getColumnNames.

	/**
	 * Get all the columns names for the model.
	 * 
	 * @param model
	 *            Model
	 * @return List<String>
	 */
	public static List<String> getColumnNames(Model model) {

		List<String> fieldList = new ArrayList<String>();
		Collection<Field> fields = ReflectionUtil.getFields(model.getClass());
		Collection<String> columnNames = null;
		for (Field field : fields) {

			columnNames = ModelHelper.getColumnNames(field);
			if (null != columnNames) {

				fieldList.addAll(columnNames);
			} else {
				// TODO: if not transient.
				fieldList.add(field.getName());
			}
		}

		return fieldList;
	} // getColumnNames.

} // E:O:F:ModelHelper.
